

app.controller('OrderAcceptCtrl', function($scope,$ionicLoading,$cordovaBarcodeScanner,$cordovaGeolocation,appFactory,$User) {
    $scope.getOrdersArray = function(mhOid){
        if(mhOid===undefined || mhOid.length<6){
            alert("请输入至少6位连续的订单编号");
            $scope.$broadcast('scroll.refreshComplete');
            return;
        }
        $ionicLoading.show({
            template: '查询中...'
        });
        param = {orderid:mhOid,uid:$User.get("id")};
        appFactory.findOrder(param).then(function(data){
            $ionicLoading.hide();
            $scope.ordersArray = data;
        }).catch(function(err){
            $ionicLoading.hide();
        });
    }
    $scope.acceptOrder = function($index){
        if(!confirm("确认领取订单？")){
            return false;
        }
        $ionicLoading.show({});
        var posOptions = {timeout: 10000, enableHighAccuracy: false};
        order = $scope.ordersArray[$index];
        $cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) {
            lat = position.coords.latitude;
            long = position.coords.longitude;
        });
        param = {orderid:order.orderid,uid:$User.get("id"),lat:lat,long:long};
        appFactory.acceptOrder(param).then(function (d) {
            $scope.ordersArray.splice($index,1);
            $ionicLoading.hide();
            alert("领单成功，请到个人中心查看");
        }).catch(function(err){
            $ionicLoading.hide();
            switch (err.errno){
                case -41:
                    alert("该订单无法被领取");
                    break;
                case -42:
                    alert("该订单已被领取");
                    break;
                case -43:
                    alert("问题订单，请反馈！！");
                    break;
                case -44:
                    alert("该订单无法领取，请反馈！！");
                    break;
                default :
                    alert("错误");
                    break;
            }
        });
    }
    $scope.barscan = function(){
        $cordovaBarcodeScanner
            .scan()
            .then(function(barcodeData) {
                var cancelled = barcodeData.cancelled;
                var result = JSON.parse(barcodeData.text);
                if(!cancelled){
                    var oid = result.OID;
                    if(oid){
                        $scope.getOrdersArray(oid)
                    }else{
                        alert('没有获取到oid');
                    }
                }else{
                    alert('扫描异常或退出扫描');
                }
            }, function(error) {
                // An error occurred
                alert('扫描异常或退出扫描');
            });
    };
})